package com.rzico.market.plugin.yanxuan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.util.DateUtils;
import com.rzico.util.HttpUtils;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;


/**
 * 网易严选工具类
 */
@Slf4j
public class YXOpenApiUtils {

    /**
     * 获取所有商品下的所有sku集合
     * @param appKey
     * @param appSecre
     */
    public static List<String> selectSku(String appKey, String appSecre){
        List<String> result = new ArrayList<String>();
        /**
         * 1.先获取所有商品id集合
         * 2.再依次循环获取商品下的sku，并添加至结果中
         */
        List<String> productList = selectProduct(appKey, appSecre);
        for (String sku : productList) {
            List<String> skuIdList = getWYYXProdectSkuId(appKey, appSecre, sku);
            result.addAll(skuIdList);
        }
        return result;
    }

    /**
     * 获取严选商品集合
     * @param appKey
     * @param appSecre
     */
    public static List<String> selectProduct(String appKey, String appSecre){
        List<String> list = new ArrayList<String>();
        String method = "yanxuan.item.id.batch.get";
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        Map<String, String> paramMap = new HashMap<String, String>();
        TreeMap<String, String> map = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(map);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        String skulist = null;
        skulist = result.substring(1, result.length() - 1);//
        String[] skuIds = skulist.split(",");
        for (String sku : skuIds) {
            list.add(sku);
        }
        return list;
    }

    /**
     * 查询商品信息
     * @param appKey
     * @param appSecre
     * @param sku skuId
     */
    public static List<String> getWYYXProdectSkuId(String appKey, String appSecre, String sku){
        List<String> resultList = new ArrayList<String>();
        String method = "yanxuan.item.batch.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("itemIds", sku);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);
        String skuList = null;
        for (Map<String,Object> map : resultMapList) {
            if (map.containsKey("skuList")) {
                skuList = map.get("skuList").toString();
                List<Map<String,Object>> skuMapList = JSONArray.parseObject(skuList,List.class);
                for(Map<String,Object> skuMap : skuMapList){
                    String skuId = null;//skuid
                    if (skuMap.containsKey("id")) {
                        skuId = skuMap.get("id").toString();
                        resultList.add(skuId);
                    }
                }
            }
        }

        return resultList;
    }

    /**
     * 查询商品单个sku信息
     * @param appKey
     * @param appSecre
     * @param sku skuId
     */
    public static Map<String, Object> selectWYYXProdectSku(String appKey, String appSecre, String sku){
        String method = "yanxuan.item.sku.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("skuId", sku);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        Map<String,Object> resultMap = JDServiceUtils.jsonToMap(result);
        String name= null;//名称
        String thumbnail= null;//缩略图
        String skuList = null;//sku信息
        String skuId = null;//skuid
        String spec1 = null;//描述
        String itemDetail = null;//详情图
        BigDecimal price = null;//价格
        String meta = null;//缩略图
        String content = null;//描述
        String policyList = null;//备注信息
        String subTitle = null;//备注信息
        if (resultMap.containsKey("name")) {
            name = resultMap.get("name").toString();
        }
        if (resultMap.containsKey("primaryPicUrl")) {
            thumbnail = resultMap.get("primaryPicUrl").toString();
        }
        if (resultMap.containsKey("skuList")) {
            skuList = resultMap.get("skuList").toString();
        }
        if (resultMap.containsKey("primarySkuId")) {
            skuId = resultMap.get("primarySkuId").toString();
        }
        if (resultMap.containsKey("simpleDesc")) {
            spec1 = resultMap.get("simpleDesc").toString();
        }
        if (resultMap.containsKey("itemDetail")) {
            itemDetail = resultMap.get("itemDetail").toString();
        }
        Map<String,Object> itemDetailMapList = JDServiceUtils.jsonToMap(itemDetail);
        if (itemDetailMapList.containsKey("policyList")) {
            policyList = itemDetailMapList.get("policyList").toString();
            List<Map<String,Object>> policyMapList = JSONArray.parseObject(policyList,List.class);
            for (Map<String,Object> policyMap : policyMapList) {
                if (policyMap.get("title").toString().contains("退换货")) {
                    subTitle = policyMap.get("title").toString();
                }
            }
        }
        price = setPrice(skuList);
        meta = setMeta(itemDetail);
        content = setContent(itemDetail);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("thumbnail", thumbnail);
        map.put("skuId", skuId);
        map.put("spec1", spec1);
        map.put("price", price);
        map.put("meta", meta);
        map.put("content", content);
        map.put("subTitle", subTitle);

        return map;
    }

    /**
     * 查询商品单个sku库存信息
     * @param appKey
     * @param appSecre
     * @param sku skuId
     */
    public static Map<String, Object> selectWYYXProdectSkuStock(String appKey, String appSecre, String sku){
        String method = "yanxuan.inventory.count.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("skuIds", sku);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);
        String stock = null;//名称
        for(Map<String,Object> map : resultMapList){
            stock = map.get("inventory").toString();
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("stock", stock);

        return resultMap;
    }

    /**
     * 查询网易严选国家编码
     * @param appKey
     * @param appSecre
     * @param countryCode 国家编码
     */
    public static Map<String, Object> selectWYYXAddressCountry(String appKey, String appSecre, String countryCode){
        String method = "yanxuan.address.country.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("countryCode", countryCode);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);


        Map<String, Object> resultMap = new HashMap<String, Object>();


        return resultMap;
    }

    /**
     * 查询网易严选省份地址编码
     * @param appKey
     * @param appSecre
     * @param countryCode 国家编码
     */
    public static Map<String, Object> selectWYYXAddressProvince(String appKey, String appSecre, String countryCode){
        String method = "yanxuan.address.province.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("countryCode", countryCode);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);


        Map<String, Object> resultMap = new HashMap<String, Object>();


        return resultMap;
    }
    /**
     * 查询网易严选城市地址编码
     * @param appKey
     * @param appSecre
     * @param provCode 省份编码
     */
    public static Map<String, Object> selectWYYXAddressCity(String appKey, String appSecre, String provCode){
        String method = "yanxuan.address.city.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("provCode", provCode);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);

        Map<String, Object> resultMap = new HashMap<String, Object>();


        return resultMap;
    }
    /**
     * 查询网易严选区县地址编码
     * @param appKey
     * @param appSecre
     * @param cityCode 城市编码
     */
    public static Map<String, Object> selectWYYXAddressDistrict(String appKey, String appSecre, String cityCode){
        String method = "yanxuan.address.district.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("cityCode", cityCode);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);


        Map<String, Object> resultMap = new HashMap<String, Object>();



        return resultMap;
    }
    /**
     * 查询网易严选乡镇(街道)地址编码
     * @param appKey
     * @param appSecre
     * @param distCode 区县编码
     */
    public static Map<String, Object> selectWYYXAddressTown(String appKey, String appSecre, String distCode){
        String method = "yanxuan.address.town.get";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("distCode", distCode);
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE);
        TreeMap<String, String> treemap = YXOpenApiUtils.packageParams(appKey, appSecre, timestamp, method, paramMap);
        Map<String, Object> params = setParam(treemap);
        String response = httpWYYXPost(params);
        Map<String, Object> reponseMap = JDServiceUtils.jsonToMap(response);
        String result = reponseMap.get("result").toString();
        List<Map<String,Object>> resultMapList = JSONArray.parseObject(result,List.class);


        Map<String, Object> resultMap = new HashMap<String, Object>();


        return resultMap;
    }


    /**
     * 设置商品sku价格
     * @param skuList
     */
    public static BigDecimal setPrice(String skuList){
        BigDecimal price = null;//价格
        Map<String, Object> map = JDServiceUtils.jsonToMap(skuList.substring(1, skuList.length() - 1));
        price = (BigDecimal) map.get("yanxuanPrice");
        return price;
    }


    /**
     * 设置商品sku轮播图
     * @param itemDetail
     */
    public static String setMeta(String itemDetail) {
        String meta = null;
        Map<String, Object> map = JDServiceUtils.jsonToMap(itemDetail);
        List<String> imageList = new ArrayList<String>();
        String img1 = map.get("picUrl1").toString();
        String img2 = map.get("picUrl2").toString();
        String img3 = map.get("picUrl3").toString();
        String img4 = map.get("picUrl4").toString();
        if (StringUtils.isNotEmpty(img1)) {
            imageList.add(img1);
        }
        if (StringUtils.isNotEmpty(img2)) {
            imageList.add(img2);
        }
        if (StringUtils.isNotEmpty(img3)) {
            imageList.add(img3);
        }
        if (StringUtils.isNotEmpty(img4)) {
            imageList.add(img4);
        }
        Map<String, Object> metaMap = new HashMap<String, Object>();
        metaMap.put("video", "");
        metaMap.put("images", imageList);
        meta = JSON.toJSONString(metaMap);
        return meta;
    }

    /**
     * 设置商品sku详情图
     * @param itemDetail
     */
    public static String setContent(String itemDetail) {
        StringBuffer content = new StringBuffer();
        List<String> list = new ArrayList<String>();
        if (!itemDetail.contains("https")) {

        } else {
            Map<String, Object> map = JDServiceUtils.jsonToMap(itemDetail);
            String detailHtml = map.get("detailHtml").toString();
            String[] images = detailHtml.split("\"");
            for (String str : images) {
                if (str.contains("http") && !list.contains(str)) {
                    list.add(str);
                }
            }
        }
        if (0 < list.size()) {
            content.append("<p>");
            for (String str : list) {
                content.append("<img class=\"wscnph\" src=\"" + str + "\" width=\"100%\" />");
            }
            content.append("</p>");
        }
        return content.toString();
    }

    /**
     * 获取不同值得Integer集合
     * @param dbSkuList
     * @param skuList
     * @return
     */
    public static List<String> compareSku(List<String> dbSkuList, List<String> skuList){
        List<String> resultList = new ArrayList<String>();
        for (String i : skuList) {
            String sku = "wyyx-" + i;
            if (!dbSkuList.contains(sku)) {
                resultList.add(i);
            }
        }

        return resultList;
    }

    /**
     * 组装参数，包括sign值的生成
     * @param appKey appKey
     * @param appSecret appSecret
     * @param timestamp timestamp
     * @param method method
     * @param paramMap paramMap
     * @return treeMap
     */
    public static TreeMap<String, String> packageParams(String appKey, String appSecret, String timestamp, String method,
                                                        Map<String, String> paramMap) {
        //将请求参数按名称排序
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("appKey", appKey);
        treeMap.put("method", method);
        treeMap.put("timestamp", timestamp);
        if (null != paramMap) {
            treeMap.putAll(paramMap);
        }
        //遍历treeMap，将参数值进行拼接
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = treeMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            sb.append(key).append("=");
            sb.append(treeMap.get(key));
        }
        //参数值拼接的字符串收尾添加appSecret值
        String waitSignStr = appSecret + sb.toString() + appSecret;
        //获取MD5加密后的字符串
        String sign = MD5Utils.getMD5Str(waitSignStr).toUpperCase();
        treeMap.put("sign", sign);
        return treeMap;
    }

    /**
     * 设置http请求参数
     * @param map
     * @return
     */
    public static Map<String, Object> setParam(TreeMap<String, String> map){
        Map<String, Object> params = new HashMap<String, Object>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            params.put(key, value);
        }
        return params;
    }

    /**
     * 网易严选发送http请求
     * @param params
     * @return
     */
    public static String httpWYYXPost(Map<String, Object> params){
        String host = "http://openapi-test.you.163.com";
        String path = "/channel/api.json";
        String result = HttpUtils.httpPost(host+path, params);
        return result;
    }

}
